import React, { useEffect, useState } from 'react'
import request from '../../utils/request'
import { connect } from 'react-redux'
import { Dispatch } from 'redux'
import { RootStore } from '../../store'
import { positionListItemType } from '../../interface'
import { useNavigate } from 'react-router-dom'
import { PullToRefresh } from 'antd-mobile'
import './style.css'
// 延时器
import { sleep } from 'antd-mobile/es/utils/sleep'


const Position = (props: any) => {

    const { dispatch, dataList, tabType } = props;

    const [current, setCurrent] = useState(1)

    // 请求开关
    const [isLoading, setIsLoading] = useState(true)

    const navigate = useNavigate()

    useEffect(() => {
        if (isLoading) {
            dispatch((dispatch: Dispatch) => {
                // 关掉请求开关 让其在请求中不能触发多次
                setIsLoading(false)
                request({
                    url: '/api/getList',
                    method: 'post',
                    data: {
                        type: tabType,
                        current: current
                    }
                }).then(res => {
                    dispatch({ type: 'CHANGE_DATA_LIST', data: res.data })

                    // 打开请求开关
                    setIsLoading(true)
                })
            })
        }
    }, [tabType, current])

    // 跳转详情
    const toDetail = (id: string) => {
        navigate(`/detail/${id}`)
    }

    // 上拉加载
    const scroll = (e: any) => {
        const { target: { scrollTop, scrollHeight, clientHeight } } = e

        // 滚动条总体的高度 - 滚动条距离顶部的位置 - 在减去页面高度 < 10
        if (scrollHeight - scrollTop - clientHeight < 10) {
            setCurrent(current + 1)
        }

    }

    // 下拉刷新
    const refresh = async () => {
        await sleep(2000)

        return Promise.resolve()
    }

    return <div className="position-box" onScroll={(e) => scroll(e)}>
        <PullToRefresh onRefresh={() => refresh()}>
            {
                dataList.length && dataList.map((item: positionListItemType, idx: number) => {
                    return <div key={idx} onClick={() => toDetail(item.id)}>
                        <div><img src={item.img} alt="" /></div>
                        <div>
                            <h1>{item.title}</h1>
                            <p>{item.word}</p>
                        </div>
                    </div>
                })
            }
        </PullToRefresh>
    </div>

}

// 获取redux 数据
const mapStateToProps = (state: RootStore) => {
    console.log(state)
    return {
        ...state.positionReducer,
        ...state.commonReducer
    }
}

// Dispatch 为redux提供数据类型  修改redux中的数据
const mapDispatchToProsp = (dispatch: Dispatch) => {
    return { dispatch }
}

export default connect(mapStateToProps, mapDispatchToProsp)(Position)